import React, { Component } from 'react'
import { message, Select, Button, Table, Card, Input, Cascader } from 'antd'

import {
  reqGetMessageBoard,
  reqSearchMessageBoard,
  reqUpdateMessageBoardStatus,
} from '../../api'
import { getReqData } from '../../utils'
import { formateDateById } from '../../utils/dateUtils'
import { PAGE_SIZE } from '../../config'

const Option = Select.Option

class MessageBoard extends Component {
  constructor(props) {
    super(props)

    this.pageNum = 1
    this.columnsInfo = [
      {
        align: 'center',
        title: '姓名',
        width: 80,
        dataIndex: 'name',
      },
      {
        align: 'center',
        width: 150,
        title: '手机号码',
        dataIndex: 'phone',
      },
      {
        align: 'center',
        title: '留言信息',
        dataIndex: 'textarea',
        ellipsis: true,
      },
      {
        align: 'center',
        title: '状态',
        width: 200,
        render: (product) => {
          const { status } = product

          return (
            <span>
              <Select
                value={status}
                onChange={(value) => this.setMessageStatus(product, value)}
                style={{ width: 150 }}
              >
                <Option value="0" key="0">
                  工作人员未读
                </Option>
                <Option value="1" key="1">
                  客户不接电话
                </Option>
                <Option value="2" key="2">
                  客户仅咨询
                </Option>
                <Option value="3" key="3">
                  客户没有意向
                </Option>
                <Option value="4" key="4">
                  客户有意向
                </Option>
              </Select>
            </span>
          )
        },
      },
      {
        align: 'center',
        title: '时间',
        width: 150,
        render: (product) => {
          const { _id } = product
          return <span>{formateDateById(_id)}</span>
        },
      },
    ]
    this.options = [
      {
        value: 'status',
        label: '按状态搜索',
        children: [
          {
            value: '0',
            label: '工作人员未读',
          },
          {
            value: '1',
            label: '客户不接电话',
          },
          {
            value: '2',
            label: '客户仅咨询',
          },
          {
            value: '3',
            label: '客户无意向',
          },
          {
            value: '4',
            label: '客户有意向',
          },
        ],
      },
      {
        value: 'name',
        label: '按姓名搜索',
      },
      {
        value: 'phone',
        label: '按手机号搜索',
      },
      {
        value: 'message',
        label: '按留言信息搜索',
      },
    ]

    this.state = {
      products: { total: 0, list: [] },
      loading: false,
      searchType: 'message',
      searchKeyWord: '',
      status: '',
    }
  }

  /**
   * 修改留言的状态
   * 修改 this.status.products.list 中的status
   */
  setMessageStatus = async (product, status) => {
    let { products } = this.state
    const { _id } = product
    products.list.forEach((item) => {
      if (item._id === _id) {
        item.status = status
      }
    })
    const { result } = await reqUpdateMessageBoardStatus({ _id, status })
    if (!getReqData(result)) {
      message.error(result.data.msg)
      return false
    }
    this.setState({ products })
  }

  /**
   * 获取指定页码的数据
   */
  getProducts = async (pageNum = 1) => {
    this.pageNum = pageNum // 让别的方法也能看到当前页
    let { searchKeyWord, searchType, status } = this.state

    this.setState({ loading: true })

    // 如果搜索关键字有值，说明需要搜索分页，否则就是一般分页
    let result

    // 有关键字，并且不是按照状态搜索。
    if (searchKeyWord !== '' && status === '') {
      result = await reqSearchMessageBoard(
        {
          page: pageNum,
          size: PAGE_SIZE,
          searchType,
          searchKeyWord,
        },
        pageNum
      )
    } else if (status !== '') {
      // 如果按照状态搜索，那么忽略关键字。
      result = await reqSearchMessageBoard(
        {
          page: pageNum,
          size: PAGE_SIZE,
          status,
        },
        pageNum
      )
    } else {
      result = await reqGetMessageBoard(pageNum, PAGE_SIZE)
    }

    const data = getReqData(result.result)
    if (!data) {
      message.error(result.data.msg)
      return false
    }

    this.setState({ products: data, loading: false })
  }

  /**
   * 级联中的变化
   */
  onChange = (info) => {
    this.setState({ searchType: '', searchKeyWord: '', status: '' })

    if ('status' === info[0]) this.setState({ status: info[1] })
    else this.setState({ searchType: info[0] })
  }

  /**
   *
   */
  getTitle = () => (
    <div>
      <Cascader
        placeholder="搜索条件"
        defaultValue={['message']}
        options={this.options}
        onChange={this.onChange}
      />

      <Input
        disabled={this.state.status !== ''}
        placeholder="关键字"
        style={{ width: 100, margin: '0 15px' }}
        onChange={(e) => this.setState({ searchKeyWord: e.target.value })}
      />

      <Button
        type="primary"
        onClick={() => {
          this.getProducts()
        }}
      >
        搜索
      </Button>
    </div>
  )

  init = async () => {
    this.setState({ loading: true })
    const { result } = await reqGetMessageBoard()
    const products = getReqData(result)
    if (!products) {
      message.error(result.data.msg)
      return null
    }

    this.setState({ products, loading: false })
  }

  componentDidMount() {
    this.init()
  }

  render() {
    const { loading, products } = this.state
    if (products.list === []) return

    return (
      <Card title={this.getTitle()}>
        <Table
          loading={loading}
          bordered
          rowKey="_id"
          dataSource={products.list}
          columns={this.columnsInfo}
          pagination={{
            current: this.pageNum, // 搜索的时候会重置 this.pageNum
            defaultPageSize: PAGE_SIZE,
            showQuickJumper: true,
            total: products.total,
            onChange: this.getProducts,
          }}
          locale={{ emptyText: '暂无数据' }}
        />
      </Card>
    )
  }
}

export default MessageBoard
